package com.yc.sole.erp.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.sole.common.domain.StateCountResp;
import com.yc.sole.erp.dto.ShipmentDto;
import com.yc.sole.erp.entity.Shipment;
import com.yc.sole.erp.mapper.ShipmentMapper;
import com.yc.sole.erp.request.ShipmentQueryReq;
import com.yc.sole.framework.mybatis.page.Paging;
import com.yc.sole.framework.mybatis.util.PageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务接口实现
 *
 * @author yizuomin
 * @date 2024-01-16
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ShipmentRepository extends ServiceImpl<ShipmentMapper, Shipment> {

    /**
     * 新增
     *
     * @param shipmentDto
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public Long saveShipment(ShipmentDto shipmentDto) {
        Shipment entity = new Shipment();
        BeanUtil.copyProperties(shipmentDto, entity);
        this.save(entity);
        return entity.getId();
    }

    /**
     * 通过Id修改
     *
     * @param shipmentDto
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateShipmentById(ShipmentDto shipmentDto) {
        Shipment entity = new Shipment();
        BeanUtil.copyProperties(shipmentDto, entity);
        this.updateById(entity);
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteShipmentByIds(Set<Long> ids) {
        this.removeByIds(ids);
    }

    /**
     * 根据id获取
     *
     * @param ids
     * @return RestResult
     */
    public List<ShipmentDto> selectShipmentByIds(Set<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(this.listByIds(ids), ShipmentDto.class);
    }

    /**
     * 根据id获取
     *
     * @param id
     * @return RestResult
     */
    public ShipmentDto selectShipmentById(Long id) {
        return BeanUtil.copyProperties(this.getById(id), ShipmentDto.class);
    }

    /**
     * 分页查询
     *
     * @param page
     * @return RestResult
     */
    public Paging<ShipmentDto> selectShipmentPage(Paging page, ShipmentQueryReq queryReq) {
        LambdaQueryWrapper<Shipment> wrapper = Wrappers.<Shipment>lambdaQuery()
                .eq(Objects.nonNull(queryReq.getCustomerId()), Shipment::getCustomerId, queryReq.getCustomerId())
                .eq(Objects.nonNull(queryReq.getShipmentType()), Shipment::getShipmentType, queryReq.getShipmentType())
                .like(CharSequenceUtil.isNotBlank(queryReq.getShipmentNo()), Shipment::getShipmentNo, queryReq.getShipmentNo())
                .and(CharSequenceUtil.isNotBlank(queryReq.getKeyword()),
                        w -> w
                                .or().like(Shipment::getCustomerName, queryReq.getKeyword())
                                .or().like(Shipment::getRemark, queryReq.getKeyword())
                                .or().like(Shipment::getShipmentNo, queryReq.getKeyword())
                                .or().like(Shipment::getTrackingNo, queryReq.getKeyword())
                                .or().like(Shipment::getCarrier, queryReq.getKeyword())
                                .or().like(Shipment::getRecipientName, queryReq.getKeyword())
                                .or().like(Shipment::getRecipientPhoneNum, queryReq.getKeyword())
                                .or().like(Shipment::getRecipientAddress, queryReq.getKeyword())
                )
                .orderByDesc(Shipment::getId);
        if (CollUtil.isNotEmpty(queryReq.getShipmentDateRange())
                && CharSequenceUtil.isNotBlank(queryReq.getShipmentDateRange().get(0))
                && CharSequenceUtil.isNotBlank(queryReq.getShipmentDateRange().get(1))) {
            wrapper.between(Shipment::getShipmentDate, queryReq.getShipmentDateRange().get(0), queryReq.getShipmentDateRange().get(1));
        }
        return PageUtil.pageCopy(this.page(PageUtil.toMybatisPage(page), wrapper), ShipmentDto.class);
    }

    /**
     * 查询送货状态的数量
     *
     * @param queryReq
     * @return
     */
    /*public List<StateCountResp> selectDeliveryStateCount(ShipmentQueryReq queryReq) {
        return this.baseMapper.selectDeliveryStateCount(queryReq);
    }*/

    /**
     * 查询送货类型的数量
     *
     * @param queryReq
     * @return
     */
    public List<StateCountResp> selectShipmentTypeCount(ShipmentQueryReq queryReq) {
        return this.baseMapper.selectShipmentTypeCount(queryReq);
    }

    /**
     * 查询客户应付款
     *
     * @return
     */
    public Map<Long, BigDecimal> selectCustomerAmount() {
        LambdaQueryWrapper<Shipment> wrapper = Wrappers.<Shipment>lambdaQuery()
                .select(Shipment::getCustomerId, Shipment::getAmount);
        return this.list(wrapper).stream()
                .collect(Collectors.groupingBy(Shipment::getCustomerId, Collectors.reducing(BigDecimal.ZERO, Shipment::getAmount, BigDecimal::add)));
    }
}
